package cn.kgc.common.resulthandler;

import cn.kgc.common.annotation.IgnoreResultAdviceAnnotation;
import cn.kgc.vo.Result;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>将控制器返回的结果封装成Result</p>
 *
 * @author 石浩杰
 * @since 2022年09月24日 9:25
 */
@ControllerAdvice("cn.kgc.controller")
public class ResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        if(returnType.getMethod().isAnnotationPresent(IgnoreResultAdviceAnnotation.class)){
            return false;
        }
        return true;
    }

    //将控制器中方法的返回值封装成Result对象
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        //获得进入控制器请求地址
        String uri=request.getURI().toString();
        if (body==null){  //如果控制器的返回值是Null的话，将结果封装成result对象
            return Result.builder().code(200).data(null).message("success").requestURL(uri).build();
        }else if (body instanceof Result){
            return (Result)body;
        }else {
            return Result.builder().code(200).data(body).message("success").requestURL(uri).build();
        }
    }
}
